#!/usr/bin/env python3
import csv
from datetime import datetime, date, timedelta
import fileinput
from json import loads
from pprint import pprint
from os.path import abspath, dirname, join, exists
from os import makedirs

ROOT = dirname(abspath(__file__))

with fileinput.input() as f:
    for i in f:
        data = loads(i)
        lastUpdateTime = data['lastUpdateTime']
        for i in data['ticketList']:
            businessDate = i['businessDate']
            businessDate = date(*map(int,businessDate.split("-")))
            onDays = i['onDays']
            上映日期 = str(businessDate-timedelta(days=(onDays)))
            name = i['filmName']
            dirpath = join(ROOT, "film", 上映日期[:7])
            filepath = join(dirpath, name+".csv")
            if not exists(filepath):
                makedirs(dirpath, exist_ok=True)
                with open(filepath, 'w', encoding='utf-8-sig') as f:
                    w = csv.writer(f)
                    w.writerows([
                        ['电影', name],
                        ['编号', i['filmCode']],
                        ['上映日期', 上映日期],
                        [],
                        [
                            "时间",
                            "累计票房(亿元)",
                            "当日票房(万元)",
                            "网售占比 %",
                            "排片占比 %",
                            "上座率 %",
                        ],
                    ])

            with open(filepath, 'a', encoding='utf-8-sig') as f:
                w = csv.writer(f)
                w.writerow([
                    lastUpdateTime,
                    i['upToNowBox']/10000000000.0,
                    i['box']/1000000.0,
                    i['onlineRate'].rstrip("%"),
                    i['arrangingRate']/100.0,
                    i['occupancy']/100.0,
                ])
